package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.domain.CheckGroup;
import com.itheima.domain.Setmeal;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealService;
import com.itheima.util.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page = setmealMapper.selectByCondition(queryString);
        long total = page.getTotal();
        List<CheckGroup> result = page.getResult();
        return new PageResult(total, result);
    }

    //新增套餐
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealMapper.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());
        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealMapper.findAll();
        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        //为模板提供数据,用于生成静态页面
        map.put("setmealList", list);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setmealMapper.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "mobile_setmeal_" + setmeal.getId() + ".html", map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //声明输出流
        Writer writer = null;
        try {
            //获取模板对象
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            writer = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, writer);
            //释放资源
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除套餐
    public void delete(Integer id) {
        Jedis resource = jedisPool.getResource();
        String img = setmealMapper.findById(id).getImg();
        //删除关联关系
        setmealMapper.deleteAssociation(id);
        //删除redis中的图片
        resource.srem(RedisConstant.SETMEAL_PIC_RESOURCES, img);
        //删除七牛云中的图片
        QiniuUtils.deleteFileFromQiniu(img);
        //删除套餐
        setmealMapper.delete(id);
        resource.close();
        //当删除套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //根据id查询套餐
    public Setmeal findById(Integer setmealId) {
        return setmealMapper.findById(setmealId);
    }

    //根据套餐id查询对应的检查组id
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        List<Integer> list = setmealMapper.findCheckGroupIdsBySetmealId(setmealId);
        return list;
    }

    //编辑
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //编辑套餐
        setmealMapper.edit(setmeal);
        //删除原来的关联关系
        setmealMapper.deleteAssociation(setmeal.getId());
        //添加新的关联关系
        setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        //当编辑套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //查询所有
    public List<Setmeal> findAll() {
        return setmealMapper.findAll();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealMapper.findSetmealCount();
    }

    @Override
    public Map<String, Object> getSetmealReportMoneyDate(String value) {
        return setmealMapper.findSetmealReportMoneyCount(value);
    }

    //绑定套餐和检查组的多对多关系
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmealId", id);
            map.put("checkgroupId", checkgroupId);
            setmealMapper.setSetmealAndCheckGroup(map);
        }
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
    }

}
